import React, {FC, useEffect, useRef, useState} from "react";
import {Menu, Dropdown, Space, Tag, Modal, Form, Input, Button, Upload, message, Image, Avatar} from 'antd';
import {inject, observer} from "_mobx-react@6.3.1@mobx-react";
import {reg, roleList} from "../utils"
import {baseURL} from "../api/ajax";
import {useNavigate} from "react-router-dom";
import api from "../api";

const PageHead: FC<any> = ({MobxData}) => {
    const {userInfo, changeUserInfo} = MobxData;
    const navigate = useNavigate();

    const [visible, setVisible] = React.useState(false);
    const [confirmLoading, setConfirmLoading] = React.useState(false);
    const [modalTitle, setModalTitle] = React.useState("");
    const [form] = Form.useForm();

    let [img_src, setImg_src] = useState("点击选择要上传到头像");
    const imgFile: any = useRef();

    const handleOk = () => {
        if (modalTitle === "修改密码") {
            // 校验表单
            form.validateFields().then(values => {
                // 变换加载状态
                setConfirmLoading(true);
                form.submit();
            })
        } else if (modalTitle === "修改头像") {
            // 判断是否选择了图片
            if (imgFile.current.files.length === 0) {
                message.info("请选择图片再提交");
                return;
            }
            // 判断是否是图片
            if (imgFile.current.files[0].type.indexOf("image") === -1) {
                message.info("请选择图片文件");
                return;
            }
            // 变换加载状态
            setConfirmLoading(true);
            // 上传头像
            const file = imgFile.current.files[0]
            const form = new FormData()  // 实例化一个表单对象
            form.append("file", file)
            // 上传请求
            api.changeImg(form).then(res => {
                if (res.code === 200) {
                    message.success(res.msg);
                    // 改变MobxData数据
                    userInfo.img = res.path;
                    changeUserInfo(userInfo)
                    // 关闭弹窗
                    setVisible(false);
                    // 变换加载状态
                    setConfirmLoading(false);
                } else {
                    message.error(res.msg);
                }
            })
        }
    };

    return userInfo._id && (
        <div className="page-head"
             style={{height: "100%", display: "flex", justifyContent: "space-between", alignItems: "center"}}>
            <h1 style={{fontSize: "30px", margin: 0}}>教务管理系统</h1>
            <div>
                <Dropdown placement="bottom" arrow={true} trigger={['click', 'hover']} overlay={
                    <Menu items={[
                        {
                            label: <span>个人中心</span>, key: 'personalCenter', onClick: () => {
                                navigate("/main/mine")
                            }
                        },
                        {
                            label: <span>修改密码</span>, key: 'changePassword', onClick: () => {
                                setModalTitle('修改密码');
                                setVisible(true)
                            }
                        },
                        {
                            label: <span>修改头像</span>, key: 'modifyAvatar', onClick: () => {
                                setModalTitle('修改头像');
                                setVisible(true)
                            }
                        },
                        {
                            label: <span>退出登录</span>, key: 'signOut', onClick: () => {
                                Modal.confirm({
                                    title: '退出提示',
                                    content: '确定要退出吗？',
                                    onOk() {
                                        sessionStorage.clear();
                                        navigate('/login');
                                    },
                                });
                            }
                        },
                    ]}/>
                }>
                    <a onClick={e => e.preventDefault()}>
                        <img style={{height: "40px", width: "40px", borderRadius: "50%"}}
                             src={userInfo.img.replace(/public/, baseURL) || require('../assets/avatar.jpg')} alt=""/>
                        <Space style={{color: "black", margin: "0 10px", fontSize: "18px"}}>{userInfo.username}</Space>
                        <Tag color="#f50">{roleList.find(item => item!.id == userInfo.role)?.name}</Tag>
                    </a>
                </Dropdown>
            </div>

            <Modal
                title={modalTitle}
                visible={visible}
                onOk={handleOk}
                confirmLoading={confirmLoading}
                onCancel={() => setVisible(false)}
            >{
                modalTitle === '修改密码' ? (
                    <Form form={form} name="basic" onFinish={(values) => {
                        delete values.confirmPassword;
                        // console.log(values);
                        // 修改密码
                        api.changeuserpass(values).then(res => {
                            if (res.code === 200) {
                                message.success(res.msg);
                                sessionStorage.clear();
                                changeUserInfo({});
                                // 关闭弹窗
                                setVisible(false);
                                navigate("/login");
                            } else {
                                message.error(res.msg);
                            }
                        })

                        // 变换加载状态
                        setConfirmLoading(false);
                    }} layout="vertical">
                        <Form.Item label="旧密码" name="oldPassword"
                                   rules={[
                                       {required: true, message: '旧密码是必填项'},
                                       {
                                           pattern: reg.password,
                                           message: '请输入6-16的密码包含数字、字母、字符中的两种'
                                       }
                                   ]}>
                            <Input.Password type="password" placeholder="请输入旧密码"/>
                        </Form.Item>
                        <Form.Item dependencies={['confirmPassword']} label="新密码" name="newPassword"
                                   rules={[
                                       {required: true, message: '新密码是必填项'},
                                       {
                                           pattern: reg.password,
                                           message: '请输入6-16的密码包含数字、字母、字符中的两种'
                                       },
                                       ({getFieldValue}) => ({
                                           validator(_, value) {
                                               if (!value || getFieldValue('confirmPassword') === value) {
                                                   return Promise.resolve();
                                               }
                                               return Promise.reject(new Error('两次输入的密码不一致'));
                                           },
                                       }),
                                   ]}>
                            <Input.Password type="password" placeholder="请输入新密码"/>
                        </Form.Item>
                        <Form.Item dependencies={['newPassword']} label="确认密码" name="confirmPassword"
                                   rules={[
                                       {required: true, message: '确认密码是必填项'},
                                       {pattern: reg.password, message: '请输入6-16的密码包含数字、字母、字符中的两种'},
                                       ({getFieldValue}) => ({
                                           validator(_, value) {
                                               if (!value || getFieldValue('newPassword') === value) {
                                                   return Promise.resolve();
                                               }
                                               return Promise.reject(new Error('两次输入的密码不一致'));
                                           },
                                       }),
                                   ]}>
                            <Input.Password type="password" placeholder="请确认密码"/>
                        </Form.Item>
                    </Form>
                ) : (
                    <div style={{
                        display: "flex",
                        justifyContent: "center",
                        alignItems: "center",
                        width: "100%",
                        height: "180px",
                        border: "1px dashed black",
                        borderRadius: "10px",
                        margin: "0 auto"
                    }} onClick={() => {
                        imgFile.current.click()
                    }}>
                        <span>{img_src}</span>
                        <input ref={imgFile} onChange={() => {
                            setImg_src(imgFile.current.files[0].name)
                        }} type="file" id="file-img" name="img" style={{display: "none"}}/>
                    </div>
                )
            }

            </Modal>
        </div>
    )
}

export default inject('MobxData')(observer(PageHead));